<template>
  <section>
    <div class="wp-product-header">
      <div>
        <span
          >总计：合计金额：<span class="wp-amount">{{
           totalSumAmount
          }}</span>元</span>
        <span
          >折后合计金额：<span class="wp-amount">{{discountTotalSumAmount }}</span>元</span
        >
      </div>
      <el-button
type="warning" @click.native="onOpenPanel" icon="el-icon-plus"  v-if="canModify || isCreate"
        >添加产品</el-button>
    </div>
    <div :style="{ height: height + 'px', overflow: 'auto' }">
      <el-table
        show-summary
        stripe
        v-loading="loading"
        :key="talbekey"
        :data="productList"
        :height="height"
        :summary-method="getSummaries"
        class="wp-product-table"
      >
        <el-table-column
          label="产品名称"
          prop="productName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="产品类型" prop="productType" :formatter="formatterProductType" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="产品型号" prop="productModel" show-overflow-tooltip> </el-table-column>
        <el-table-column label="单位" prop="unit"> </el-table-column>
        <el-table-column label="销售数量" prop="productNum" width="120">
          <template slot-scope="scope">
            <el-input-number
              v-if="isCreate || !scope.row.orderNo"
              :min="1"
              size="mini"
              style="width: 100px"
              @change="calculation(scope.row)"
              @blur="onBlur($event, '销售数量')"
              v-model="scope.row.productNum"
              placeholder="请输入"
            ></el-input-number>
            <span v-else>{{ scope.row.productNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="销售单价（元）" prop="price" width="150">
          <template slot-scope="scope">
            <el-input-number
              v-if="isCreate || !scope.row.orderNo"
              size="mini"
              :precision="2"
              :min="0"
              @change="calculation(scope.row)"
              @blur="onBlur($event, '销售单价')"
              v-model="scope.row.price"
              placeholder="请输入"
            ></el-input-number>
            <span v-else>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="折扣（%）" prop="discountRate" width="120">
          <template slot-scope="scope">
            <el-input-number
              v-if="isCreate || !scope.row.orderNo"
              controls-position="right"
              size="mini"
              :precision="2"
              :step="0.1"
              :max="1"
              style="width: 100px"
              @change="calculation(scope.row)"
              v-model="scope.row.discountRate"
              placeholder="折扣"
            ></el-input-number>
            <span v-else>{{ scope.row.discountRate || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合计金额" prop="totalAmount" width="100">
          <template slot="header">
            <el-tooltip
:content="totalTooltip" placement="top"
              ><i class="header-icon el-icon-question"></i
            ></el-tooltip>
            <span>合计金额</span>
          </template>
          <template slot-scope="scope">
            {{ scope.row.totalAmount || calculation(scope.row, "totalAmount") }}
          </template>
        </el-table-column>
        <el-table-column
          label="折后合计金额"
          prop="discountTotalAmount"
          width="100"
        >
          <template slot="header">
            <div class="wp-table-header__tooltip">
              <el-tooltip
:content="discountTotalTooltip" placement="top"
                ><i class="header-icon el-icon-question"></i
              ></el-tooltip>
              <el-tooltip
content="折后合计金额" placement="top"
                ><span>折后合计金额</span></el-tooltip
              >
            </div>
          </template>
          <template slot-scope="scope">
            {{
              scope.row.discountTotalAmount ||
              calculation(scope.row, "discountTotalAmount")
            }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center"  v-if="canModify ||isCreate">
          <template slot-scope="scope" >
              <el-link v-if="!isCreate && (!scope.row.orderNo || scope.row.orderNo == null)" type="success" @click="saveProduct(scope.row)">确 定</el-link>
              <el-link  type="danger" @click="handleDelete(scope.$index, scope.row)">删 除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Drawer ref="orderProductDrawer" width="55%">
      <Product-search
        :plist="productList"
        :lableInfo="lableInfo"
        @save="handleSave"
      />
    </Drawer>
  </section>
</template>

<script>
import Drawer from '@/components/Drawer'
import ProductSearch from '@/views/eims/components/productSearch/index'
import Mixins from '../../mixins'
import {toDecimal} from '@/utils'
export default {
  name: 'SalesProductInfoIndex',
  mixins: [Mixins],
  props: {
    isCreate: { type: Boolean, default: true },
    canModify: { type: Boolean, default: false },
    orderActualAmount: {type: [String, Number], default: 0},
    param: {type: Object,
      default: () => {
        return {}
      }
    },
    height: {
      type: Number,
      default: 180
    }
  },
  components: { Drawer, ProductSearch },
  data () {
    return {
      productList: [],
      loading: false,
      sums: [],
      totalSumAmount: 0,
      discountTotalSumAmount: 0,
      talbekey: '',
      lableInfo: { numLable: '销售数量', priceLable: '销售单价' },
      totalTooltip: '合计金额 = 产品数量 X 销售单价',
      discountTotalTooltip: '折后合计金额 = 合计金额 X 折扣（%）'
    }
  },
  created () {
    if (!this.isCreate) {
      this.getOrderProductList(this.param.orderNo)
    }
  },
  watch: {
    discountTotalSumAmount (nVal) {
      this.$emit('update:orderActualAmount', nVal)
    },
    productList (nVal) {
      this.$emit('update:list', nVal)
    }
  },
  methods: {
    reloadList () {
      this.talbekey = Math.random()
    },
    getOrderProductList (orderNo) {
      this.loading = true
      this.requestOption('getOrderProductList', orderNo, res => {
        this.productList = res.data || []
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    saveProduct (row) {
      if (this.validate(row)) {
        const params = row
        params.orderNo = this.param.orderNo
        this.requestOption('saveSalesOrderDetail', params, res => {
          this.getOrderProductList(this.param.orderNo)
          this.$emit('editAfter')
        })
      }
    },
    handleSave (data) {
      let productList = this.productList
      let isSave = true
      if (productList && productList.length >= 0) {
        for (let index = 0; index < productList.length; index++) {
          const item = productList[index]
          if (item.productCode === data.productCode) {
            productList[index] = data
            productList[index].price = productList[index].price
            isSave = false
            break
          }
        }
      } else {
        productList.unshift(data)
      }
      if (isSave) {
        productList.unshift(data)
      }
      this.reloadList()
      // this.$refs.orderProductDrawer.close()
    },
    handleDelete (index, row) {
      this.$msgBox.confirm(
        '确认删除产品' + (row.productName || '') + '?',
        () => {
          if (row.orderNo && row.orderDetailNo) {
            const params = {}
            params.orderNo = row.orderNo
            params.orderDetailNo = row.orderDetailNo
            this.requestOption('deleteSalesOrderDetail', params, res => {
            // 更新实际订单
              this.productList.splice(index, 1)
              this.$emit('editAfter')
            })
          } else {
            this.productList.splice(index, 1)
          }
        }
      )
    },
    calculation (row, key) {
      row.totalAmount =
        toDecimal(Math.round(row.price * row.productNum * 100) / 100)
      row.discountTotalAmount =
        toDecimal(Math.round(
          row.price * row.productNum * (row.discountRate || 1) * 100
        ) / 100)
      return row[key]
    },
    onBlur (e, text) {
      if (!e.target.value) {
        this.$msgBox.error(text + '不能为空')
      }
    },
    validate (data) {
      if (!data.price) {
        this.$msgBox.error('销售单价不能为空', 200)
        return false
      }
      if (!data.productNum) {
        this.$msgBox.error('销售数量不能为空', 200)
        return false
      }
      return true
    },
    onOpenPanel () {
      this.$refs.orderProductDrawer.show()
    },
    onClosePanel () {
      this.$refs.orderProductDrawer.close()
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = ''
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] = Math.round(sums[index] * 100) / 100
        }
      })
      this.sums = sums
      this.totalSumAmount = toDecimal(sums[7]||0)
      this.discountTotalSumAmount = toDecimal(sums[8]||0)
      return sums
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-product-header {
  text-align: right;
  margin-bottom: 5px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-end;
}
.wp-product-main {
  background: skyblue;
}

.wp-table-expand {
  font-size: 0;
}
.wp-table-expand >>> label {
  color: #99a9bf;
}
.wp-table-expand >>> .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}
.wp-talbe-item-btn {
  text-align: right;
}

.wp-product-table >>> .el-table__footer-wrapper,
.wp-product-table >>> .el-table__footer {
  display: none;
}
.wp-remark {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: flex-start;
  font-size: 8px;
  font-weight: 600;
  color: rgba(255, 136, 0, 0.726);
}
.wp-remark div {
  margin-top: 5px;
}
.wp-amount {
  font-size: 14px;
  font-weight: 600;
}
</style>
